<!-- 课程管理(模块) => 课程列表(菜单) => 台账操作列(课代表管理按钮) => 点开 => 创建课代表账号按钮 => 点开后展示此组件 -->
<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800">
    <el-alert class="!mb-[10px]" type="error" :closable="false">
      {{ t('course.index.addAssistantTip') }}
    </el-alert>
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-row v-if="formData.id === undefined">
        <el-col :span="12">
          <el-form-item :label="t('systemUser.fields.username')" prop="username">
            <el-input
              v-model="formData.username"
              :placeholder="t('common.inputTextPlaceholder') + t('systemUser.fields.username')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('systemUser.fields.password')" prop="password">
            <el-input
              v-model="formData.password"
              :placeholder="t('common.inputTextPlaceholder') + t('systemUser.fields.password')"
              show-password
              type="password"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="t('assistant.fields.nickname')" prop="nickname">
            <el-input
              v-model="formData.nickname"
              :placeholder="t('common.inputTextPlaceholder') + t('assistant.fields.nickname')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('systemUser.fields.mobile')" prop="mobile">
            <el-input
              v-model="formData.mobile"
              maxlength="11"
              :placeholder="t('common.inputTextPlaceholder') + t('systemUser.fields.mobile')"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { CommonStatusEnum, WorkingStatusEnum } from '@/utils/constants'
import { handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import { FormRules } from 'element-plus'

defineOptions({ name: 'AddCourseAssistant' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  nickname: '',
  jobCode: '',
  deptId: '',
  mobile: '',
  email: '',
  identity: '',
  id: undefined,
  username: '',
  password: '',
  sex: undefined,
  postIds: [],
  remark: '',
  status: CommonStatusEnum.ENABLE,
  workingStatus: WorkingStatusEnum.WORKING,
  imrStatus: WorkingStatusEnum.WORKING,
  roleIds: []
})
const formRules = reactive({
  username: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('systemUser.fields.username'),
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('systemUser.fields.password'),
      trigger: 'blur'
    }
  ],
  nickname: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('systemUser.fields.nickname'),
      trigger: 'blur'
    }
  ],
  jobCode: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('systemUser.fields.jobCode'),
      trigger: 'blur'
    }
  ],
  mobile: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('systemUser.fields.mobile'),
      trigger: 'blur'
    },
    {
      pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
      message: t('systemUser.form.mobileError'),
      trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('systemUser.fields.email'),
      trigger: 'blur'
    },
    {
      type: 'email',
      message: t('systemUser.form.emailError'),
      trigger: ['blur', 'change']
    }
  ],
  workingStatus: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('systemUser.fields.workingStatus'),
      trigger: 'change'
    }
  ],
  deptId: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('systemUser.fields.deptId'),
      trigger: 'change'
    }
  ]
} as FormRules)

const formRef = ref() // 表单 Ref
const deptList = ref<Tree[]>([]) // 树形结构

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await UserApi.getUser(id)
    } finally {
      formLoading.value = false
    }
  }
  // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as UserApi.UserVO
    if (formType.value === 'create') {
      // 部门给个100
      data.deptId = 100
      // 一定是子账号!!
      data.subUser = true
      // 随便给个工号
      data.jobCode = `A${data.mobile}`
      await UserApi.createAssistantUser(data)
      message.success(t('common.createSuccess'))
    } else {
      // 暂时没有修改功能 只能新增 后续再说
      await UserApi.updateUser(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    nickname: '',
    jobCode: '',
    deptId: '',
    mobile: '',
    email: '',
    identity: '',
    id: undefined,
    username: '',
    password: '',
    sex: undefined,
    postIds: [],
    remark: '',
    status: CommonStatusEnum.ENABLE,
    workingStatus: WorkingStatusEnum.WORKING,
    imrStatus: WorkingStatusEnum.WORKING,
    roleIds: []
  }
  formRef.value?.resetFields()
}
</script>
